﻿/***********************************************************************
 * CLR 版本: 4.0.30319.225
 * 工程名称: $projectname$
 * 命名空间: Toulr.Core.Services
 * 文件名称: ShopService
 * 描    述: 提供店铺信息管理 维护功能实现
 * 作    者: 18901309129@189.cn
 * 登录用户: hyyu
 * 创建时间: 2011-5-28 16:03:37
 * 创建年份: 2011
 * Update History: 
 ***********************************************************************/

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Toulr.Domains;
using Toulr.Domains.Business;
using Toulr.Domains.System;
using Toulr.Models;
using Toulr.Models.Account;
using Toulr.Models.Shop;
using Toulr.Services;
using Toulr.Util.Geography;
using Toulr.Util.Logging;

namespace Toulr.Core.Services
{
    /// <summary>
    /// 提供店铺信息管理 维护功能实现
    /// </summary>
    public class ShopService : IShopService
    {
        #region 店铺分享

        /// <summary>
        /// 获取店铺被分享次数
        /// </summary>
        /// <param name="shopId">
        /// 店铺ID
        /// </param>
        /// <returns></returns>
        /// hyyu 20110610
        public ActionResult<int> GetShopShareInCount(int shopId)
        {
            if (shopId <= 0)
            {
                LogHelper.Logger.Debug("获取店铺分享次数失败，店铺ID不正确："+shopId);
                return new ActionResult<int>(1, "获取店铺分享次数失败，店铺ID不正确：" + shopId, -1);
            }
            var shopCount = from evaluation in DomainContext.Instance.ShopEvaluations
                            where evaluation.ShopId == shopId
                            select evaluation.ShareInCount;
            if (shopCount.Count() == 0)
            {
                return new ActionResult<int>(1, "获取店铺分享次数失败，没有找到对应的记录，店铺ID：" + shopCount, 1);
            }
            return new ActionResult<int>(0, "获取店铺分享次数成功", shopCount.ToArray()[0]);
        }

        /// <summary>
        /// 获取店铺被分享次数
        /// </summary>
        /// <param name="shop">
        /// 店铺对象，注意店铺ID不能为空
        /// </param>
        /// <returns></returns>
        /// hyyu 20110610
        public ActionResult<int> GetShopShareInCount(Shop shop)
        {
            if(shop==null)
            {
                LogHelper.Logger.Debug("获取店铺分享次数失败，店铺对象为空");
                return new ActionResult<int>(1, "获取店铺分享次数失败，店铺对象为空", -1);
            }
            return GetShopShareInCount(shop.Id);
        }

        /// <summary>
        /// 分享店铺 在数据库中添加一次分享
        /// </summary>
        /// <param name="shop">
        /// 店铺对象，注意店铺ID不能为空
        /// </param>
        /// <returns></returns>
        /// hyyu 20110609
        public ActionResult<int> ShopShareIn(Shop shop)
        {
            if (shop == null)
            {
                LogHelper.Logger.Debug("添加店铺分享失败，店铺对象为空");
                return new ActionResult<int>(1, "添加店铺分享失败，店铺对象为空", -1);
            }
            return ShopShareIn(shop.Id);
        }

        /// <summary>
        /// 分享店铺 在数据库中添加一次分享
        /// </summary>
        /// <param name="shopId">
        /// 店铺ID
        /// </param>
        /// <returns></returns>
        /// hyyu 20110609
        public ActionResult<int> ShopShareIn(int shopId)
        {
            if (shopId <= 0)
            {
                LogHelper.Logger.Debug("添加店铺分享失败，店铺ID不正确："+shopId);
                return new ActionResult<int>(1, "添加店铺分享失败，店铺ID不正确：" + shopId, -1);
            }
            //if (QueryShop(shopId) == null || QueryShopEvaluation(shopId) == null)
            //{
            //    LogHelper.Logger.Debug("添加店铺分享失败，店铺对象不存在，店铺ID：" + shopId);
            //    return new ActionResult<int>(1, "添加店铺分享失败，店铺对象不存在，店铺ID：" + shopId, -1);
            //}
            try
            {
                //IRepository<ShopEvaluation> repository=new Repository<ShopEvaluation>();
                //repository.Update(DomainContext.Instance.ShopEvaluations.First(x => x.ShopId == shopId));
            }
            catch (Exception ex)
            {
                
                throw;
            }

            throw new NotImplementedException();
        }

        #endregion

        #region 店铺的评论与回复

        /// <summary>
        /// 添加对一个评论的支持（我认为不错）
        /// </summary>
        /// <param name="evaluationDetailId">
        /// 评论ID
        /// </param>
        /// <returns></returns>
        /// hyyu20110611
        public ActionResult<int> AddShopEvaluationAbet(int evaluationDetailId)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 添加对一个评论的支持（我认为不错）
        /// </summary>
        /// <param name="evaluationDetail">
        /// 评论对象
        /// 注意ID不能为空
        /// </param>
        /// <returns></returns>
        /// hyyu20110611
        public ActionResult<int> AddShopEvaluationAbet(ShopEvaluationDetail evaluationDetail)
        {
            throw new NotImplementedException();
        }

        private static IList<ShopEvaluationDetail> QueryShopEvaluationDetail(int id,int shopId,int userId)
        {
            try
            {
                var objs = from detail in DomainContext.Instance.ShopEvaluationDetails
                           select detail;
                if (id > 0)
                    objs = objs.Where(detail => detail.Id == id);
                if (shopId > 0)
                    objs = objs.Where(detail => detail.ShopId == shopId);
                if (userId > 0)
                    objs = objs.Where(detail => detail.UserId == userId);
                objs = objs.OrderBy(detail => detail.EvaluationTime);
                return objs.ToArray();
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("获取店铺评论列表出错："+ex.Message,ex);
                return null;
            }
        }

        /// <summary>
        /// 获取店铺评论（分）详细内容列表
        /// </summary>
        /// <param name="shopId">店铺ID</param>
        /// <returns></returns>
        /// hyyu 20110529 
        public ActionResult<IList<ShopEvaluationDetail>> GetShopEvaluationDetails(int shopId)
        {
            if(shopId<=0)
            {
                LogHelper.Logger.Debug("获取店铺评论列表失败，店铺ID不正确："+shopId);
                return new ActionResult<IList<ShopEvaluationDetail>>(1, "获取店铺评论列表失败，店铺ID不正确：" + shopId, null);
            }
            var resultObj = QueryShopEvaluationDetail(-1, shopId, -1);
            if(resultObj==null)
                return new ActionResult<IList<ShopEvaluationDetail>>(1, "获取店铺评论列表失败，详情请查看日志", null);
            return new ActionResult<IList<ShopEvaluationDetail>>(0, "获取店铺列表成功", resultObj);
        }

        /// <summary>
        /// 获取店铺评论（分）详细内容列表
        /// </summary>
        /// <param name="shop">店铺对象</param>
        /// <returns></returns>
        /// hyyu 20110529 
        public ActionResult<IList<ShopEvaluationDetail>> GetShopEvaluationDetails(Shop shop)
        {
            if(shop==null)
            {
                LogHelper.Logger.Debug("获取店铺评论列表失败，店铺对象为空");
                return new ActionResult<IList<ShopEvaluationDetail>>(1, "获取店铺评论列表失败，店铺对象为空", null);
            }
            return GetShopEvaluationDetails(shop.Id);
        }

        /// <summary>
        /// 添加店铺的一个评论（分）
        /// </summary>
        /// <param name="evaluationDetail">
        /// 评论对象
        /// </param>
        /// <returns></returns>
        /// hyyu 20110529 
        public ActionResult<ShopEvaluationDetail> AddShopEvaluationDetail(ShopEvaluationDetail evaluationDetail)
        {
            try
            {
                var repository = new Repository<ShopEvaluationDetail>();
                repository.Add(evaluationDetail);
                ShopEvaluationCompute(evaluationDetail.ShopId);//重新计算店铺汇总分并更新
                return new ActionResult<ShopEvaluationDetail>(0, "添加店铺评论成功", evaluationDetail);
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("添加店铺评论出错："+ex.Message,ex);
                return new ActionResult<ShopEvaluationDetail>(1, "添加店铺评论出错，详细请查看日志",null);
            }
        }

        /// <summary>
        /// 修改店铺一个的评论（分）
        /// </summary>
        /// <param name="evaluationDetail">
        /// 评论对象
        /// 注意：若某个属性未发生改变，应该将原有的值赋给属性
        /// </param>
        /// <returns></returns>
        /// hyyu 20110529 
        public ActionResult<ShopEvaluationDetail> UpdateShopEvaluationDetail(ShopEvaluationDetail evaluationDetail)
        {
            if(evaluationDetail==null)
            {
                LogHelper.Logger.Debug("修改店铺评论失败，店铺评论对象为空");
                return new ActionResult<ShopEvaluationDetail>(1, "修改店铺评论失败，店铺评论对象为空",null);
            }
            if(evaluationDetail.Id<=0)
            {
                LogHelper.Logger.Debug("修改店铺评论失败，店铺评论对象ID不正确："+evaluationDetail.Id);
                return new ActionResult<ShopEvaluationDetail>(1,"修改店铺评论失败，店铺评论对象ID不正确："+evaluationDetail.Id,null);
            }

            var tmp = QueryShopEvaluationDetail(evaluationDetail.Id,-1,-1);
            if(tmp==null || tmp.Count==0)
            {
                LogHelper.Logger.Debug("修改店铺评论失败，店铺评论对象不存在，ID：" + evaluationDetail.Id);
                return new ActionResult<ShopEvaluationDetail>(1, "修改店铺评论失败，店铺评论对象不存在，ID：" + evaluationDetail.Id, null);
            }

            try
            {
                var repository = new Repository<ShopEvaluationDetail>();
                repository.Update(evaluationDetail);
                ShopEvaluationCompute(evaluationDetail.ShopId);//重新计算店铺汇总分并更新
                return new ActionResult<ShopEvaluationDetail>(0,"修改店铺评论成功",evaluationDetail);
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("修改店铺评论出错："+ex.Message,ex);
                return new ActionResult<ShopEvaluationDetail>(1, "修改店铺评论出错，详细请查看日志。",null);
            }

        }

        /// <summary>
        /// 删除店铺一个的评论（分）
        /// </summary>
        /// <param name="evaluationDetail">
        /// 评论对象
        /// </param>
        /// <returns></returns>
        /// hyyu 20110529 
        public ActionResult<ShopEvaluationDetail> DeleteShopEvaluationDetail(ShopEvaluationDetail evaluationDetail)
        {
            if (evaluationDetail == null)
            {
                LogHelper.Logger.Debug("删除店铺评论失败，店铺评论对象为空");
                return new ActionResult<ShopEvaluationDetail>(1, "删除店铺评论失败，店铺评论对象为空", null);
            }
            if (evaluationDetail.Id <= 0)
            {
                LogHelper.Logger.Debug("删除店铺评论失败，店铺评论对象ID不正确：" + evaluationDetail.Id);
                return new ActionResult<ShopEvaluationDetail>(1, "删除店铺评论失败，店铺评论对象ID不正确：" + evaluationDetail.Id, null);
            }

            var tmp = QueryShopEvaluationDetail(evaluationDetail.Id, -1, -1);
            if (tmp == null || tmp.Count == 0)
            {
                LogHelper.Logger.Debug("删除店铺评论失败，店铺评论对象不存在，ID：" + evaluationDetail.Id);
                return new ActionResult<ShopEvaluationDetail>(1, "删除店铺评论失败，店铺评论对象不存在，ID：" + evaluationDetail.Id, null);
            }

            try
            {
                var repository = new Repository<ShopEvaluationDetail>();
                repository.Delete(evaluationDetail);
                ShopEvaluationCompute(evaluationDetail.ShopId);//重新计算店铺汇总分并更新
                return new ActionResult<ShopEvaluationDetail>(0, "删除店铺评论成功", evaluationDetail);
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("删除店铺评论出错：" + ex.Message, ex);
                return new ActionResult<ShopEvaluationDetail>(1, "删除店铺评论出错，详细请查看日志。", null);
            }
        }

        /// <summary>
        /// 删除店铺一个的评论（分）
        /// </summary>
        /// <param name="id">
        /// 评论对象ID
        /// </param>
        /// <returns></returns>
        /// hyyu 20110529 
        public ActionResult<ShopEvaluationDetail> DeleteShopEvaluationDetail(int id)
        {
            return DeleteShopEvaluationDetail(new ShopEvaluationDetail {Id = id});
        }

        private static IList<EvaluationReply> QueryEvaluationReplys(int id,int shopId, int shopEvaluationDetailId)
        {
            try
            {
                var result = from reply in DomainContext.Instance.EvaluationReplys
                             select reply;
                if (id > 0)
                {
                    result = result.Where(reply => reply.Id == id);
                }
                if(shopId>0)
                {
                    result = result.Where(reply => reply.ShopId == shopId);
                }
                if(shopEvaluationDetailId>0)
                {
                    result = result.Where(reply => reply.ShopEvaluationDetailId == shopEvaluationDetailId);
                }
                result = result.OrderBy(reply => reply.Id);
                return result.ToArray();
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("查询店铺所有的评论回复出错："+ex.Message,ex);
                return null;
            }
        }

        /// <summary>
        /// 获取店铺某个评论的所有回复
        /// </summary>
        /// <param name="shopEvaluationDetail">评论对象</param>
        /// <returns></returns>
        /// hyyu 20110602
        public ActionResult<IList<EvaluationReply>> GetEvaluationReplys(ShopEvaluationDetail shopEvaluationDetail)
        {
            if(shopEvaluationDetail==null)
            {
                LogHelper.Logger.Debug("查询评论的所有回复失败，店铺回复对象为空");
                return new ActionResult<IList<EvaluationReply>>(1, "查询店铺的所有回复失败，店铺回复对象为空",null);
            }
            if(shopEvaluationDetail.Id<=0)
            {
                LogHelper.Logger.Debug("查询评论的所有回复失败，店铺回复对象ID不正确："+shopEvaluationDetail.Id);
                return new ActionResult<IList<EvaluationReply>>(1, "查询店铺的所有回复失败，店铺回复对象ID不正确：" + shopEvaluationDetail.Id, null);
            }
            var resultObj = QueryEvaluationReplys(0,0, shopEvaluationDetail.Id);
            if(resultObj==null)
            {
                LogHelper.Logger.Debug("查询评论的所有回复失败，详细查看日志。");
                return new ActionResult<IList<EvaluationReply>>(1, "查询评论的所有回复失败，详细查看日志。", null);
            }
            return new ActionResult<IList<EvaluationReply>>(1, "查询评论的所有回复成功。",resultObj);

        }

        /// <summary>
        /// 获取店铺的所有评论回复
        /// </summary>
        /// <param name="shop">店铺对象</param>
        /// <returns></returns>
        /// hyyu 20110602
        public ActionResult<IList<EvaluationReply>> GetEvaluationReplys(Shop shop)
        {
            if (shop == null)
            {
                LogHelper.Logger.Debug("查询店铺评论的所有回复失败，店铺对象为空");
                return new ActionResult<IList<EvaluationReply>>(1, "查询店铺评论的所有回复失败，店铺对象为空", null);
            }
            if (shop.Id <= 0)
            {
                LogHelper.Logger.Debug("查询店铺评论的所有回复失败，店铺对象ID不正确：" + shop.Id);
                return new ActionResult<IList<EvaluationReply>>(1, "查询店铺评论的所有回复失败，店铺对象ID不正确：" + shop.Id, null);
            }
            var resultObj = QueryEvaluationReplys(0,shop.Id,0);
            if (resultObj == null)
            {
                LogHelper.Logger.Debug("查询店铺评论的所有回复失败，查询店铺评论的所有回复失败。");
                return new ActionResult<IList<EvaluationReply>>(1, "查询评论的所有回复失败，详细查看日志。", null);
            }
            return new ActionResult<IList<EvaluationReply>>(1, "查询店铺评论的所有回复成功。", resultObj);
        }

        /// <summary>
        /// 添加一个评论的回复
        /// </summary>
        /// <param name="evaluationReply">
        /// 评论回复对象
        /// 注意ID为标识列并且下列字段不能为空
        /// ShopEvaluationDetailId
        /// UserId
        /// ReplyContext
        /// ShopId
        /// </param>
        /// <returns></returns>
        /// hyyu 20110602
        public ActionResult<EvaluationReply> AddEvaluationReply(EvaluationReply evaluationReply)
        {
            if(evaluationReply==null)
            {
                LogHelper.Logger.Debug("添加评论回复失败，评论回复对象为空");
                return new ActionResult<EvaluationReply>(1, "添加评论回复失败，评论回复对象为空。", null);
            }
            if (evaluationReply.ShopEvaluationDetailId<=0)
            {
                LogHelper.Logger.Debug("添加评论回复失败，评论ID不正确："+evaluationReply.ShopEvaluationDetailId);
                return new ActionResult<EvaluationReply>(1, "添加评论回复失败，评论ID不正确：" + evaluationReply.ShopEvaluationDetailId, null);
            }
            if(evaluationReply.ShopId<=0)
            {
                LogHelper.Logger.Debug("添加评论回复失败，店铺ID不正确：" + evaluationReply.ShopId);
                return new ActionResult<EvaluationReply>(1, "添加评论回复失败，店铺ID不正确：" + evaluationReply.ShopId, null);
            }
            if (evaluationReply.UserId <= 0)
            {
                LogHelper.Logger.Debug("添加评论回复失败，用户ID不正确：" + evaluationReply.UserId);
                return new ActionResult<EvaluationReply>(1, "添加评论回复失败，用户ID不正确：" + evaluationReply.UserId, null);
            }
            if (string.IsNullOrEmpty(evaluationReply.ReplyContext))
            {
                LogHelper.Logger.Debug("添加评论回复失败，回复内容为空");
                return new ActionResult<EvaluationReply>(1, "添加评论回复失败，回复内容为空：", null);
            }
            var shopEvaluationDetails = QueryShopEvaluationDetail(evaluationReply.ShopEvaluationDetailId, -1, -1);
            if(shopEvaluationDetails==null || shopEvaluationDetails.Count==0)
            {
                LogHelper.Logger.Debug("添加评论回复失败，评论不存在，评论ID："+evaluationReply.ShopEvaluationDetailId);
                return new ActionResult<EvaluationReply>(1, "添加评论回复失败，评论不存在，评论ID：" + evaluationReply.ShopEvaluationDetailId, null);
            }

            var user = UserContextService.GetUser(evaluationReply.UserId);
            if (user == null)
            {
                LogHelper.Logger.Debug("添加评论回复失败，用户不存在，用户ID：" + evaluationReply.UserId);
                return new ActionResult<EvaluationReply>(1, "添加评论回复失败，用户不存在，用户ID：" + evaluationReply.UserId, null);
            }

            //防止店铺ID不正确，把评论的店铺ID直接给回复对象
            evaluationReply.ShopId = shopEvaluationDetails[0].ShopId;

            //店铺不需要验证是否存在了，因为评论存在 hyyu 20110602
            
            try
            {
                var repository = new Repository<EvaluationReply>();
                repository.Add(evaluationReply);
                return new ActionResult<EvaluationReply>(0,"添加评论回复成功",evaluationReply);
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("添加评论回复时出错："+ex.Message);
                return new ActionResult<EvaluationReply>(1, "添加评论回复时出错，详情查看日志",null);
            }

        }

        /// <summary>
        /// 修改店铺评论回复内容
        /// </summary>
        /// <param name="evaluationReplyId">回复对象ID</param>
        /// <param name="replyContext">回复内容</param>
        /// <returns></returns>
        /// hyyu 20110602
        public ActionResult<EvaluationReply> UpdateEvaluationReply(int evaluationReplyId, string replyContext)
        {
            if (string.IsNullOrEmpty(replyContext))
            {
                LogHelper.Logger.Debug("修改评论回复内容失败，评论回复为空");
                return new ActionResult<EvaluationReply>(1, "修改评论回复内容失败，评论回复为空", null);
            }
            var evaluationReply = QueryEvaluationReplys(0,0, evaluationReplyId);
            if(evaluationReply==null || evaluationReply.Count==0)
            {
                LogHelper.Logger.Debug("修改评论回复内容失败，评论回复ID不存在："+evaluationReplyId);
                return new ActionResult<EvaluationReply>(1, "修改评论回复内容失败，评论回复ID不存在："+evaluationReplyId,null);
            }

            try
            {
                evaluationReply[0].ReplyContext = replyContext;
                var repository = new Repository<EvaluationReply>();
                repository.Update(evaluationReply[0]);
                return new ActionResult<EvaluationReply>(0,"修改评论回复成功。",evaluationReply[0]);
                
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("修改评论回复内容出错："+ex.Message,ex);
                return new ActionResult<EvaluationReply>(1, "修改评论回复内容出错，详情查看日志。", null);
            }
        }

        /// <summary>
        /// 修改店铺评论回复
        /// </summary>
        /// <param name="evaluationReply">
        /// 回复对象
        /// 注意若某个属性未发生改变，应该将原有的值赋给属性
        /// </param>
        /// <returns></returns>
        /// hyyu 20110602
        public ActionResult<EvaluationReply> UpdateEvaluationReply(EvaluationReply evaluationReply)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 删除店铺评论回复
        /// </summary>
        /// <param name="evaluationReply">
        /// 回复对象
        /// </param>
        /// <returns></returns>
        /// hyyu 20110602
        public ActionResult<EvaluationReply> DeleteEvaluationReply(EvaluationReply evaluationReply)
        {
            if(evaluationReply==null)
            {
                LogHelper.Logger.Debug("删除评论回复失败，回复对象为空。");
                return new ActionResult<EvaluationReply>(1, "删除评论回复失败，回复对象为空。",null);
            }
            var evaluationReplys = QueryEvaluationReplys(evaluationReply.Id, 0, 0);
            if(evaluationReplys==null || evaluationReplys.Count==0)
            {
                LogHelper.Logger.Debug("删除评论回复失败，回复对象ID不正确："+evaluationReply.Id);
                return new ActionResult<EvaluationReply>(1, "删除评论回复失败，回复对象ID不正确：" + evaluationReply.Id, null);
            }
            try
            {
                var repository = new Repository<EvaluationReply>();
                repository.Delete(evaluationReply);
                return new ActionResult<EvaluationReply>(0,"删除评论回复成功。",evaluationReply);
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("删除评论回复出错："+ex.Message,ex);
                return new ActionResult<EvaluationReply>(1,"删除评论回复出错，详情查看日志。",null);
            }
        }

        #endregion

        #region 店铺所属分类扩展特性维护

        /// <summary>
        /// 获取店铺可选的评分项列表 用于初始化用户输入界面
        /// </summary>
        /// <param name="shop"></param>
        /// <returns></returns>
        /// hyyu 20110608
        public ActionResult<IList<InfoCategoriesProperty>> GetOptionalEvaluation(Shop shop)
        {
            if (shop == null)
                return new ActionResult<IList<InfoCategoriesProperty>>(1, "获取店铺可选评分项失败，店铺对象为空", null);
            if (shop.ShopCategoryId <= 0)
            {
                if (shop.Id <= 0)
                {
                    return new ActionResult<IList<InfoCategoriesProperty>>(1, "获取店铺可选评分项失败，店铺ID不正确：" + shop.Id, null);
                }
                var obj = QueryShop(shop.Id);
                if (obj == null)
                    return new ActionResult<IList<InfoCategoriesProperty>>(1, "获取店铺可选评分项失败，店铺对象不存在，店铺ID：" + shop.Id,null);
                shop = obj;
            }
            return GetOptionalEvaluation(shop.ShopCategoryId);
        }

        /// <summary>
        /// 获取店铺可选的评分项列表 用于初始化用户输入界面
        /// </summary>
        /// <param name="infoCategoriesId"></param>
        /// <returns></returns>
        /// hyyu 20110608
        public ActionResult<IList<InfoCategoriesProperty>> GetOptionalEvaluation(int infoCategoriesId)
        {
            var lstInfoCategoriesProperty = QueryOptionalPropertys(-1, infoCategoriesId, 2, null);
            if (lstInfoCategoriesProperty.Count == 0)
                LogHelper.Logger.Debug("但没有找到符合条件的分类评分项，分类ID：" + infoCategoriesId);
            return new ActionResult<IList<InfoCategoriesProperty>>(0, "获取分类评分项成功", lstInfoCategoriesProperty);
        }

        /// <summary>
        /// 获取店铺可选的扩展属性列表
        /// </summary>
        /// <param name="shop"></param>
        /// <returns></returns>
        /// hyyu 20110528 
        public ActionResult<IList<InfoCategoriesProperty>> GetOptionalPropertys(Shop shop)
        {
            if (shop == null)
                return new ActionResult<IList<InfoCategoriesProperty>>(1, "获取店铺可选扩展属性失败，店铺信息为空", null);
            if(shop.ShopCategoryId<=0)
            {
                if(shop.Id<=0)
                {
                    return new ActionResult<IList<InfoCategoriesProperty>>(1, "获取店铺可选扩展属性失败，店铺ID不正确：" + shop.Id, null);
                }
                var shops = QueryShop(shop.Id);
                if(shops==null)
                    return new ActionResult<IList<InfoCategoriesProperty>>(1,"获取店铺可选扩展属性失败，店铺对象不存在，店铺ID："+shop.Id,null);
            }
            return GetOptionalPropertys(shop.ShopCategoryId);
        }

        /// <summary>
        /// 获取分类信息可选的扩展属性列表
        /// </summary>
        /// <param name="infoCategoriesId"></param>
        /// <returns></returns>
        /// hyyu 20110528 
        public ActionResult<IList<InfoCategoriesProperty>> GetOptionalPropertys(int infoCategoriesId)
        {
            var lstInfoCategoriesProperty =QueryOptionalPropertys(-1,infoCategoriesId, 1, null);
            if (lstInfoCategoriesProperty.Count == 0)
                LogHelper.Logger.Debug("但没有找到符合条件的分类信息扩展属性，分类ID：" + infoCategoriesId);
            return new ActionResult<IList<InfoCategoriesProperty>>(0, "获取分类可选扩展属性成功", lstInfoCategoriesProperty);
        }

        private static IList<InfoCategoriesProperty> QueryOptionalPropertys(int id,int infoCategoriesId, int typeId, string propName)
        {
            try
            {
                var objs = from property in DomainContext.Instance.InfoCategoriesPropertys
                           select property;
                if (id > 0)
                    objs = objs.Where(property => property.Id == id);
                if (infoCategoriesId > 0)
                    objs = objs.Where(property => property.InfoCategoriesId == infoCategoriesId);
                if (typeId > 0)
                    objs = objs.Where(property => property.TypeId == typeId);
                if (!string.IsNullOrEmpty(propName))
                    objs = objs.Where(property => property.PropName == propName.Trim());
                objs = objs.OrderBy(property => property.Id);

                return objs.ToArray();

            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("查询分类扩展属性结果时出现错误：" + ex.Message, ex);
                return null;
            }
        }

        private static IList<ShopProperty> QueryShopPropertys(int id,int propertyId, int shopId, string propertyName)
        {
            try
            {
                var objs = from shopProperty in DomainContext.Instance.ShopPropertys
                           select shopProperty;
                if (id > 0)
                    objs = objs.Where(shopProperty => shopProperty.Id == id);
                if (propertyId > 0)
                    objs = objs.Where(shopProperty => shopProperty.PropertyId == propertyId);
                if (shopId > 0)
                    objs = objs.Where(shopProperty => shopProperty.ShopId == shopId);
                if (!string.IsNullOrEmpty(propertyName))
                    objs = objs.Where(shopProperty => shopProperty.PropertyName == propertyName);
                objs = objs.OrderBy(shopProperty => shopProperty.Id);
                return objs.ToArray();
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("获取店铺已有的分类扩展属性列表出错：" + ex.Message, ex);
                return null;
            }
        }

        /// <summary>
        /// 获取当前店铺已有的分类扩展属性、属性值列表
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        /// hyyu 20110528 
        public ActionResult<IList<ShopProperty>> GetShopPropertys(int shopId)
        {
            var lstShopProperty = QueryShopPropertys(-1, -1, shopId, null);
            if (lstShopProperty == null)
                return new ActionResult<IList<ShopProperty>>(1, "获取店铺已有的扩展属性列表失败，详细请查看日志。", null);
            return new ActionResult<IList<ShopProperty>>(0, "获取店铺已有的扩展属性列表成功。", lstShopProperty);
        }

        /// <summary>
        /// 添加一个店铺的扩展属性信息
        /// </summary>
        /// <param name="shopProperty">
        /// 扩展属性对象
        /// 注意：除ID外任何字段都不能为空
        /// </param>
        /// <returns></returns>
        /// hyyu 20110528 
        public ActionResult<ShopProperty> AddShopProperty(ShopProperty shopProperty)
        {
            var actionResult = AddShopProperty(new List<ShopProperty> { shopProperty });
            if (actionResult.ResultCode == 0)
                return new ActionResult<ShopProperty>(0, actionResult.Tips, actionResult.Result[0]);
            return new ActionResult<ShopProperty>(1, actionResult.Tips, null);
        }

        /// <summary>
        /// 添加一组店铺的扩展属性信息
        /// </summary>
        /// <param name="shopPropertys">
        /// 扩展属性对象列表
        /// 注意：每个对象除ID外任何字段都不能为空
        /// </param>
        /// <returns></returns>
        /// hyyu 20110528 
        public ActionResult<IList<ShopProperty>> AddShopProperty(IList<ShopProperty> shopPropertys)
        {
            int sucCount = 0;//保存成功的对象数量
            int failCount = 0;//保存失败的对象数量
            IList<ShopProperty> lstSucShopProperty = new List<ShopProperty>();//保存成功的对象列表

            foreach (var property in shopPropertys)
            {
                if (property == null)
                {
                    LogHelper.Logger.Debug("保存店铺扩展属性失败。店铺扩展属性信息对象为空。");
                    failCount++;
                    continue;
                }
                if (string.IsNullOrEmpty(property.PropertyName))
                {
                    LogHelper.Logger.Debug("保存店铺扩展属性失败。扩展属性名称为空。");
                    failCount++;
                    continue;
                }
                var infoCategoriess = QueryOptionalPropertys(property.PropertyId,-1,-1,null);
                if (property.PropertyId <= 0 || infoCategoriess == null || infoCategoriess.Count == 0)
                {
                    LogHelper.Logger.Debug("保存店铺扩展属性失败。所属分类信息为空，分类信息ID：" + property.PropertyId);
                    failCount++;
                    continue;
                }
                if (property.ShopId <= 0 || QueryShop(property.ShopId) == null)
                {
                    LogHelper.Logger.Debug("保存店铺扩展属性失败。所属店铺为空，店铺ID：" + property.PropertyId);
                    failCount++;
                    continue;
                }
                var shopProperty = QueryShopPropertys(-1, property.PropertyId, property.ShopId, property.PropertyName);
                if (shopProperty != null && shopProperty.Count > 0)
                {
                    if (property.ShopId <= 0 || QueryShop(property.ShopId) == null)
                    {
                        LogHelper.Logger.Debug("保存店铺扩展属性失败。信息重复，分类ID：" + property.PropertyId + " 店铺ID：" + property.ShopId);
                        failCount++;
                        continue;
                    }
                }

                try
                {
                    var repository = new Repository<ShopProperty>();
                    repository.Add(property);
                    lstSucShopProperty.Add(property);
                    sucCount++;
                }
                catch (Exception ex)
                {
                    LogHelper.Logger.Error("保存店铺分类扩展属性出错：" + ex.Message, ex);
                    failCount++;
                }
            }

            int resultCode = 0;
            if (sucCount == 0 || failCount == shopPropertys.Count)
                resultCode = 1;

            return new ActionResult<IList<ShopProperty>>(resultCode, "共有" + sucCount + "个店铺扩展属性保存成功，" + failCount + "个店铺扩展属性保存失败，详细请查看日志。", lstSucShopProperty);

        }

        /// <summary>
        /// 更新一个店铺的扩展属性信息
        /// </summary>
        /// <param name="shopProperty">
        /// 扩展属性对象
        /// 注意：若某个属性未发生改变，应该将原有的值赋给属性
        /// </param>
        /// <returns></returns>
        /// hyyu 20110529 
        public ActionResult<ShopProperty> UpdateShopProperty(ShopProperty shopProperty)
        {
            if(shopProperty==null)
            {
                LogHelper.Logger.Debug("要更新的店铺扩展属性对象为空");
                return new ActionResult<ShopProperty>(1, "要列新的店铺扩展属性对象为空",null);
            }

            var shopPropertys = GetShopPropertys(shopProperty.Id);

            if (shopProperty.Id == 0 || shopPropertys == null || shopPropertys.Result.Count==0)
            {
                LogHelper.Logger.Debug("要更新的店铺扩展属性ID没有找到："+shopProperty.Id);
                return new ActionResult<ShopProperty>(1, "要更新的店铺扩展属性ID没有找到：" + shopProperty.Id, null);
            }
            if(string.IsNullOrEmpty(shopProperty.PropertyName))
            {
                LogHelper.Logger.Debug("要更新店表扩展属性名称为空");
                return new ActionResult<ShopProperty>(1, "要更新店表扩展属性名称为空", null);
            }
            var infoCategoriesProperties = QueryOptionalPropertys(shopProperty.PropertyId, -1, -1, null);
            if (shopProperty.PropertyId <= 0 || infoCategoriesProperties == null || infoCategoriesProperties.Count == 0)
            {
                LogHelper.Logger.Debug("更新店铺扩展属性失败。所属分类信息为空，分类信息ID：" + shopProperty.PropertyId);
                return new ActionResult<ShopProperty>(1, "更新店铺扩展属性失败。所属分类信息为空，分类信息ID：" + shopProperty.PropertyId, null);
            }
            if (shopProperty.ShopId <= 0 || QueryShop(shopProperty.ShopId) == null)
            {
                LogHelper.Logger.Debug("更新店铺扩展属性失败。所属店铺为空，店铺ID：" + shopProperty.ShopId);
                return new ActionResult<ShopProperty>(1, "更新店铺扩展属性失败。所属店铺为空，店铺ID：" + shopProperty.ShopId, null);
            }

            try
            {
                var repository = new Repository<ShopProperty>();
                repository.Update(shopProperty);
                return new ActionResult<ShopProperty>(0,"更新店铺扩展属性成功",shopProperty);
            }
            catch(Exception ex)
            {
                LogHelper.Logger.Error("更新店铺扩展属性出错："+ex.Message,ex);
                return new ActionResult<ShopProperty>(1, "更新店铺扩展属性出错：" + ex.Message,null);
            }
        }

        /// <summary>
        /// 获取店铺汇总评分值列表 用于界面显示
        /// </summary>
        /// <param name="shop">
        /// 店铺对象
        /// </param>
        /// <returns></returns>
        /// hyyu 20110529 
        public ActionResult<ShopEvaluation> GetShopEvaluation(Shop shop)
        {
            if(shop==null)
            {
                LogHelper.Logger.Debug("获取店铺汇总评分列表失败，店铺对象为空");
                return new ActionResult<ShopEvaluation>(1, "获取店铺汇总评分列表失败，店铺对象为空",null);
            }
            return GetShopEvaluation(shop.Id);
        }

        /// <summary>
        /// 获取店铺汇总评分值列表 用于界面显示
        /// </summary>
        /// <param name="shopId">
        /// 店铺ID
        /// </param>
        /// <returns></returns>
        /// hyyu 20110529 
        public ActionResult<ShopEvaluation> GetShopEvaluation(int shopId)
        {
            if(shopId<=0)
            {
                LogHelper.Logger.Debug("获取店铺汇总评分列表失败，店铺ID不正确："+shopId);
                return new ActionResult<ShopEvaluation>(1, "获取店铺汇总评分失败，店铺ID不正确：" + shopId, null);
            }
            var resultObj = QueryShopEvaluation(shopId);
            if(resultObj==null)
                return new ActionResult<ShopEvaluation>(1,"获取店铺汇总评分失败，详细请查看日志。",null);
            return new ActionResult<ShopEvaluation>(0, "获取店铺汇总评分成功，详细请查看日志。",resultObj);
        }

        private static ShopEvaluation QueryShopEvaluation(int shopId)
        {
            try
            {
                var shopEvaluation = DomainContext.Instance.ShopEvaluations.FirstOrDefault(s => s.ShopId == shopId);
                return shopEvaluation;
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("获取店铺汇总评分出错："+ex.Message,ex);
                return null;
            }
        }

        private static bool AddShopEvaluation(ShopEvaluation shopEvaluation)
        {
            try
            {
                var repository = new Repository<ShopEvaluation>();
                repository.Add(shopEvaluation);
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("添加店铺汇总评分出错："+ex.Message,ex);
                return false;
            }
        }

        private static bool DeleteShopEvaluation(ShopEvaluation shopEvaluation)
        {
            try
            {
                var repository = new Repository<ShopEvaluation>();
                repository.Delete(shopEvaluation);
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("添加店铺汇总评分出错：" + ex.Message, ex);
                return false;
            }
        }

        private static bool UpdateShopEvaluation(ShopEvaluation shopEvaluation)
        {
            try
            {
                var repository = new Repository<ShopEvaluation>();
                repository.Update(shopEvaluation);
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("修改店铺汇总评分出错：" + ex.Message, ex);
                return false;
            }
        }

        //计算店铺汇总分，并更新到数据库
        private static bool ShopEvaluationCompute(int shopId)
        {
            try
            {

                //todo 由于现在只有一处调用，且调用处可以确保店铺已经存在，不再做店铺的验证了，但如果有其它地方调用，应该考虑进行验证
                var evaluation = DomainContext.Instance.ShopEvaluationDetails.Where(detail => detail.ShopId==shopId).GroupBy(
                    detail => new
                                  {
                                      detail.ShopId,
                                      detail.ItemName1,
                                      detail.ItemName2,
                                      detail.ItemName3,
                                      detail.ItemName4,
                                      detail.ItemName5,
                                      detail.ItemName6,
                                      detail.ItemName7,
                                      detail.ItemName8,
                                      detail.ItemName9,
                                      detail.ItemName10
                                  }).Select(n => new
                                                     {
                                                         n.Key,
                                                         ItemValue1 = n.Average(detail => detail.ItemValue1),
                                                         ItemValue2 = n.Average(detail => detail.ItemValue2),
                                                         ItemValue3 = n.Average(detail => detail.ItemValue3),
                                                         ItemValue4 = n.Average(detail => detail.ItemValue4),
                                                         ItemValue5 = n.Average(detail => detail.ItemValue5),
                                                         ItemValue6 = n.Average(detail => detail.ItemValue6),
                                                         ItemValue7 = n.Average(detail => detail.ItemValue7),
                                                         ItemValue8 = n.Average(detail => detail.ItemValue8),
                                                         ItemValue9 = n.Average(detail => detail.ItemValue9),
                                                         ItemValue10 = n.Average(detail => detail.ItemValue10),
                                                         CritiqueCount = n.Select(x => x.ShopId).Count()
                                                     });

                var evaluations = evaluation.ToArray();

                if (evaluations.Length == 0)
                {
                    LogHelper.Logger.Debug("计算店铺汇总得分失败，没有获取到店铺详细评论");
                    return false;
                }

                var shopEvaluation = QueryShopEvaluation(shopId);
                if(shopEvaluation==null)
                {
                    LogHelper.Logger.Debug("计算店铺汇总得分失败，没有获取到店铺已有的汇总评分记录");
                    return false;
                }
                if(!string.IsNullOrEmpty(evaluations[0].Key.ItemName1))
                {
                    shopEvaluation.ItemName1 = evaluations[0].Key.ItemName1;
                    shopEvaluation.ItemValue1 = evaluations[0].ItemValue1;
                }
                if (!string.IsNullOrEmpty(evaluations[0].Key.ItemName2))
                {
                    shopEvaluation.ItemName2 = evaluations[0].Key.ItemName2;
                    shopEvaluation.ItemValue2 = evaluations[0].ItemValue2;
                }
                if (!string.IsNullOrEmpty(evaluations[0].Key.ItemName3))
                {
                    shopEvaluation.ItemName3 = evaluations[0].Key.ItemName3;
                    shopEvaluation.ItemValue3 = evaluations[0].ItemValue3;
                }
                if (!string.IsNullOrEmpty(evaluations[0].Key.ItemName4))
                {
                    shopEvaluation.ItemName4 = evaluations[0].Key.ItemName4;
                    shopEvaluation.ItemValue4 = evaluations[0].ItemValue4;
                }
                if (!string.IsNullOrEmpty(evaluations[0].Key.ItemName5))
                {
                    shopEvaluation.ItemName5 = evaluations[0].Key.ItemName5;
                    shopEvaluation.ItemValue5 = evaluations[0].ItemValue5;
                }
                if (!string.IsNullOrEmpty(evaluations[0].Key.ItemName6))
                {
                    shopEvaluation.ItemName6 = evaluations[0].Key.ItemName6;
                    shopEvaluation.ItemValue6 = evaluations[0].ItemValue6;
                }
                if (!string.IsNullOrEmpty(evaluations[0].Key.ItemName7))
                {
                    shopEvaluation.ItemName7 = evaluations[0].Key.ItemName7;
                    shopEvaluation.ItemValue7 = evaluations[0].ItemValue7;
                }
                if (!string.IsNullOrEmpty(evaluations[0].Key.ItemName8))
                {
                    shopEvaluation.ItemName8 = evaluations[0].Key.ItemName8;
                    shopEvaluation.ItemValue8 = evaluations[0].ItemValue8;
                }
                if (!string.IsNullOrEmpty(evaluations[0].Key.ItemName9))
                {
                    shopEvaluation.ItemName9 = evaluations[0].Key.ItemName9;
                    shopEvaluation.ItemValue9 = evaluations[0].ItemValue9;
                }
                if (!string.IsNullOrEmpty(evaluations[0].Key.ItemName10))
                {
                    shopEvaluation.ItemName10 = evaluations[0].Key.ItemName10;
                    shopEvaluation.ItemValue10 = evaluations[0].ItemValue10;
                }
                shopEvaluation.CritiqueCount=evaluations[0].CritiqueCount;
                return UpdateShopEvaluation(shopEvaluation);
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("更新店铺汇总得分出错："+ex.Message,ex);
                return false;
            }
        }

        #endregion

        #region 店铺相关

        private static IList<Shop> QueryShops(Shop shop)
        {
            var obj = from s in DomainContext.Instance.Shops
                      select s;
            try
            {
                if (shop == null)
                    return null;
                if (shop.Id > 0)
                    obj = obj.Where(s => s.Id == shop.Id);
                if (!string.IsNullOrEmpty(shop.Address))
                    obj = obj.Where(s => s.Address.Contains(shop.Address));
                if (!string.IsNullOrEmpty(shop.BizLicense))
                    obj = obj.Where(s => s.BizLicense == shop.BizLicense);
                if (shop.CityId > 0)
                    obj = obj.Where(s => s.CityId == shop.CityId);
                if (shop.CountyId > 0)
                    obj = obj.Where(s => s.CountyId == shop.CountyId);
                if (!string.IsNullOrEmpty(shop.Description))
                    obj = obj.Where(s => s.Description.Contains(shop.Description));
                if (!string.IsNullOrEmpty(shop.Features))
                    obj = obj.Where(s => s.Features.Contains(shop.Features));
                if (shop.PostCode > 0)
                    obj = obj.Where(s => s.PostCode == shop.PostCode);
                if (shop.ShopCategoryId > 0)
                    obj = obj.Where(s => s.ShopCategoryId == shop.ShopCategoryId);
                if (shop.ShopKeeperId > 0)
                    obj = obj.Where(s => s.ShopKeeperId == shop.ShopKeeperId);
                if (shop.ShopManagerId > 0)
                    obj = obj.Where(s => s.ShopManagerId == shop.ShopManagerId);
                if (!string.IsNullOrEmpty(shop.ShopName))
                    obj = obj.Where(s => s.ShopName.Contains(shop.ShopName));
                if (shop.ShoppingAreaId > 0)
                    obj = obj.Where(s => s.ShoppingAreaId == shop.ShoppingAreaId);
                if (!string.IsNullOrEmpty(shop.Traffics))
                    obj = obj.Where(s => s.Traffics.Contains(shop.Traffics));
                return obj.ToArray();

                //todo 目前没有添加的条件：店铺是否已验证、验证时间、店铺加入时间、经度、纬度、许可证号提交时间、店铺营业时间说明

            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("获取店铺列表出错：" + ex.Message, ex);
                return null;
            }
        }

        /// <summary>
        /// 获取一个店铺
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        /// hyyu 20110518
        private static Shop QueryShop(int shopId)
        {
            var shops = QueryShops(new Shop { Id = shopId });
            if (shops != null && shops.Count > 0)
                return shops[0];
            return null;
        }

        /// <summary>
        /// 获取店铺列表
        /// </summary>
        /// <returns></returns>
        /// hyyu 20110518
        public ActionResult<IList<Shop>> GetShops()
        {
            return GetShops(new Shop());
        }

        /// <summary>
        /// 获取店铺列表
        /// </summary>
        /// <param name="shop"></param>
        /// <returns></returns>
        /// hyyu 20110518
        public ActionResult<IList<Shop>> GetShops(Shop shop)
        {
            var shops = QueryShops(shop);
            if(shops==null)
                return new ActionResult<IList<Shop>>(1,"查询店铺列表失败，详情果看日志。",null);
            return new ActionResult<IList<Shop>>(0, "获取店铺列表成功",shops);
        }

        /// <summary>
        /// 添加一个店铺
        /// </summary>
        /// <param name="shop"></param>
        /// <returns></returns>
        /// hyyu 20110518
        public ActionResult<Shop> AddShop(Shop shop)
        {
            try
            {
                if (shop == null)
                {
                    LogHelper.Logger.Debug("添加店铺失败，店铺对象为空");
                    return new ActionResult<Shop>(1, "要添加的店铺信息为空", null);
                }
                if (string.IsNullOrEmpty(shop.ShopName))
                {
                    LogHelper.Logger.Debug("添加店铺失败，店铺名称为空");
                    return new ActionResult<Shop>(1, "店铺名称不能为空", null);
                }
                if (string.IsNullOrEmpty(shop.Address))
                {
                    LogHelper.Logger.Debug("添加店铺失败，店铺地址为空");
                    return new ActionResult<Shop>(1, "店铺所在地址不能为空", null);
                }
                //if (!string.IsNullOrEmpty(shop.BizLicense))//todo 新加店必须有许可证号？
                //    return new ActionResult<Shop>(1, "店铺许可证编号不能为空", null);
                if (string.IsNullOrEmpty(shop.Description))
                {
                    LogHelper.Logger.Debug("添加店铺失败，店铺描述为空");
                    return new ActionResult<Shop>(1, "店铺描述不能为空", null);
                }
                if (shop.CityId <= 0)//todo 还应该验证一下城市ID是否存在;
                {
                    LogHelper.Logger.Debug("添加店铺失败，所属城市ID不正确，城市ID："+shop.CityId);
                    return new ActionResult<Shop>(1, "店铺所属城市不能为空", null);
                }
                
                if (shop.ShopCategoryId <= 0)
                {
                    LogHelper.Logger.Debug("添加店铺失败，所属分类ID不正确，分类ID：" + shop.ShopCategoryId);
                    return new ActionResult<Shop>(1, "店铺所属类型不能为空", null);
                }
                var infoCategory = CommonService.QueryInfoCategoriess(shop.ShopCategoryId, -1, null, true);
                if(infoCategory==null || infoCategory.Count==0)
                {
                    LogHelper.Logger.Debug("添加店铺失败，所属分类不存在，分类ID：" + shop.ShopCategoryId);
                    return new ActionResult<Shop>(1, "店铺所属类型不存在", null);
                }

                if(shop.ShoppingAreaId>0 && false)//todo 验证所属商圈是否正确
                {
                    LogHelper.Logger.Debug("添加店铺失败，所属商圈不存在，商圈ID：" + shop.ShoppingAreaId);
                    return new ActionResult<Shop>(1, "所属商圈不存在", null);
                }

                shop.ShopFlag = 2;//新添加店铺的默认状态

                var repository = new Repository<Shop>();
                repository.Add(shop);
                AddShopEvaluation(new ShopEvaluation {ShopId = shop.Id});//新添的店铺默认新增一个空的汇总评分
                return new ActionResult<Shop>(0, "添加店铺信息成功", shop);
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("添加店铺出错：" + ex.Message, ex);
                return new ActionResult<Shop>(1, ex.Message, null);
            }
        }

        /// <summary>
        /// 修改店铺信息
        /// </summary>
        /// <param name="shop"></param>
        /// <returns></returns>
        /// hyyu 20110518
        public ActionResult<Shop> UpdateShop(Shop shop)
        {
            return null;
        }

        /// <summary>
        /// 删除店铺信息
        /// </summary>
        /// <param name="shop"></param>
        /// <returns></returns>
        /// hyyu 20110518
        public ActionResult<Shop> DeleteShop(Shop shop)
        {
            try
            {
                if (shop == null)
                {
                    LogHelper.Logger.Debug("删除店铺失败");
                    return new ActionResult<Shop>(1, "要删除的店铺信息不能为空", null);
                }
                
                if (QueryShop(shop.Id) == null)
                    return new ActionResult<Shop>(1, "要删除的店铺信息不存在", null);
                var repository = new Repository<Shop>();
                repository.Delete(shop);
                DeleteShopEvaluation(new ShopEvaluation {ShopId = shop.Id});
                return new ActionResult<Shop>(0, "删除店铺信息成功", null);
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("删除店铺出错：" + ex.Message, ex);
                return new ActionResult<Shop>(1, ex.Message, null);
            }
        }

        private static IList<HotShopModel> QueryAboutHotShops(int shopId,GeoPoint geoPoint, int infoCategoriesId, int range,int count)
        {
            var instance = DomainContext.Instance;

            var result = new List<HotShopModel>();
            try
            {
                var geoPointLt = new GeoPoint();
                var geoPointRb = new GeoPoint();
                if (!GetCircumscribe(geoPoint, ref geoPointLt, ref geoPointRb, range))
                    return result;
                var objs = (from shop in instance.Shops
                            join shopEvaluation in instance.ShopEvaluations on shop.Id equals
                               shopEvaluation.ShopId
                           where
                               shop.Id != shopId && shop.Latitude <= geoPointLt.Latitude &&
                               shop.Longitude >= geoPointLt.Longitude && shop.Latitude >= geoPointRb.Latitude &&
                               shop.Longitude <= geoPointRb.Longitude && shop.ShopCategoryId == infoCategoriesId
                           orderby shopEvaluation.ShareInCount descending , shopEvaluation.CritiqueCount descending
                           select
                               new
                                   {
                                       sid = shop.Id,
                                       sname = shop.ShopName,
                                       critique = shopEvaluation.CritiqueCount,
                                       shareIn = shopEvaluation.ShareInCount,
                                       grade = shopEvaluation.ItemValue1
                                   }).Take(count);


                result.AddRange(objs.ToArray().Select(obj => new HotShopModel(obj.sid, obj.sname, obj.shareIn, obj.critique, obj.grade)));

                return result;
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("查询附近热门店铺失败："+ex.Message,ex);
                return null;
            }
        }
        
        /// <summary>
        /// 获取某个点指定范围的外接矩形
        /// </summary>
        /// <param name="geoPoint"></param>
        /// <param name="geoPointLt"></param>
        /// <param name="geoPointRb"></param>
        /// <param name="range">距离 米</param>
        private static bool GetCircumscribe(GeoPoint geoPoint,ref GeoPoint geoPointLt,ref GeoPoint geoPointRb,int range)
        {
            var result = false;
            try
            {
                geoPointLt = new GeoPoint(geoPoint.Latitude + GeoUtils.GetLatitudeDelta(geoPoint, range),
                                          geoPoint.Longitude - GeoUtils.GetLongitudeDelta(geoPoint, range));
                geoPointRb = new GeoPoint(geoPoint.Latitude - GeoUtils.GetLatitudeDelta(geoPoint, range),
                                          geoPoint.Longitude + GeoUtils.GetLongitudeDelta(geoPoint, range));
                result = true;
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("计算某个点的外接矩形出错："+ex.Message);
            }
            return result;


        }

        /// <summary>
        /// 获取附近同类别热门店铺
        /// </summary>
        /// <param name="shopId">店铺ID</param>
        /// <param name="range">
        /// 半径范围 米
        /// </param>
        /// <param name="count"></param>
        /// <returns></returns>
        /// hyyu 20110614
        public ActionResult<IList<HotShopModel>> GetAboutHotShops(int shopId, int range,int count)
        {
            var shop = QueryShop(shopId);
            if(shop==null)
            {
                LogHelper.Logger.Debug("查询附近热门店铺失败，店铺不存在，店铺ID："+shopId);
                return new ActionResult<IList<HotShopModel>>(1, "查询附近热门店铺失败，店铺不存在，店铺ID：" + shopId, null);
            }
            return GetAboutHotShops(shop, range,count);
        }

        /// <summary>
        /// 获取附近同类别热门店铺
        /// </summary>
        /// <param name="shop">
        /// 店铺对象 ID和ShopCategoryId必须
        /// </param>
        /// <param name="range"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        /// hyyu 20110614
        public ActionResult<IList<HotShopModel>> GetAboutHotShops(Shop shop, int range,int count)
        {
            if(shop==null)
            {
                LogHelper.Logger.Debug("查询附近热门店铺失败，店铺对象为空");
                return new ActionResult<IList<HotShopModel>>(1, "查询附近热门店铺失败，店铺对象为空", null);
            }

            if(shop.Latitude<=0 || shop.Longitude<=0)
            {
                LogHelper.Logger.Debug(string.Format("查询附近热门店铺失败，正纬度不正确。x={0};y={1}",shop.Longitude,shop.Latitude));
                return new ActionResult<IList<HotShopModel>>(1, string.Format("查询附近热门店铺失败，纬度不正确。x={0};y={1}", shop.Longitude, shop.Latitude), null);
            }

            if(shop.ShopCategoryId<=0)
            {
                LogHelper.Logger.Debug("查询附近热闹店铺失败，店铺分类不正确。分类ID："+shop.ShopCategoryId);
                return new ActionResult<IList<HotShopModel>>(1,"查询附近热门店铺失败，店铺分类不正确。分类ID："+shop.ShopCategoryId,null);
            }

            var hotShops = QueryAboutHotShops(shop.Id,new GeoPoint(shop.Latitude, shop.Longitude), shop.ShopCategoryId, range,count);
            if (hotShops == null)
            {
                return new ActionResult<IList<HotShopModel>>(1, "查询附近热门店铺失败，详情查看日志。", null);
            }
            return new ActionResult<IList<HotShopModel>>(0, "查询附近热门店铺成功。", hotShops);
        }

        #endregion
         
    }
}
